<template>
	<view class="wrap">
		<view v-if="!loading">
			<view style="margin-top: 50rpx;background-color: #fff;border-radius: 16rpx;padding: 20rpx;">
				<u-form :model="model" :rules="rules" ref="uForm" :errorType="errorType">
					<u-form-item label-width="150" :label-position="labelPosition" label="账户" prop="username">
						<u-input :border="border" placeholder="请输入账户" v-model="model.username" type="text"></u-input>
					</u-form-item>
					<u-form-item label-width="150" :label-position="labelPosition" label="密码" prop="password">
						<u-input :password-icon="true" :border="border" type="password" v-model="model.password"
							placeholder="请输入密码"></u-input>
					</u-form-item>
				</u-form>
			</view>
			<view style="margin-top: 50rpx;"><u-button type="primary" @click="submit">登录</u-button></view>
		</view>
		<view v-if="loading" style="display: flex;align-items: center;justify-content: center;margin-top: 20rpx;">
			<u-loading mode="flower"></u-loading>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			let that = this;
			return {
				loading:true,
				model: {
					username: '',
					password: '',
				},
				rules: {
					name: [{
						required: true,
						message: '请输入用户名',
						trigger: 'blur',
					}, ],
					password: [{
						required: true,
						message: '请输入密码',
						trigger: ['change', 'blur'],
					}],
				},
				labelPosition: 'left',
				errorType: ['toast'],
			};
		},
		onLoad() {
			const username = uni.getStorageSync('username');
			let password = uni.getStorageSync("password")
			if(username&&password){
				this.model.username = username
				this.model.password = password
				this.login()
			}else{
				this.loading = false
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			submit() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						console.log('验证通过');
						this.login()
					} else {
						console.log('验证失败');
					}
				});
			},
			
			login(){
				this.$u.post("/driver/login",this.model).then(res=>{
					if(res.code===200){
						uni.setStorageSync('username',this.model.username);
						uni.setStorageSync('password',this.model.password)
						getApp().globalData.token = res.token
						getApp().globalData.userId = res.loginUser.userId
						getApp().globalData.driverInfo = res.driverInfo
						getApp().globalData.loginUser = res.loginUser 
						getApp().globalData.transportationCompany = res.transportationCompany
						uni.switchTab({
							url: "/pages/index/index"
						})
					}
				})
			}
		}
	};
</script>

<style scoped lang="scss">
	.wrap {
		padding: 30rpx;
	}

	.agreement {
		display: flex;
		align-items: center;
		margin: 40rpx 0;

		.agreement-text {
			padding-left: 8rpx;
			color: $u-tips-color;
		}
	}
</style>